import {ProForm} from "@ant-design/pro-components";
import {AutoComplete} from "antd";
import React, {useState} from "react";

let timer: any

const MapAutoComplete = (props: any) => {

  const {mapRef, latLnt, style, label, rules, name} = props

  const [addressList, setAddressList] = useState([])

  return <ProForm.Item label={label} rules={rules} name={name}>
    <AutoComplete
      placeholder={"请输入"} options={addressList} style={{...style}}
      onSelect={(data: string) => {
        console.log('onSelect', data);
        addressList.forEach((e: any, i) => {
          if (e.label === data) {
            console.log(`select e = ${e}`, e)
            // form.setFieldsValue({workerAddressLat: e.location.lat, workerAddressLng: e.location.lng})
            latLnt({lat: e.location.lat, lng: e.location.lng})
            mapRef.current?.addMarker(e.location)
          }
        })
      }}
      onSearch={(value) => {
        console.log('search value = ', value)
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        timer = setTimeout(() => {
          let autoComplete = mapRef.current?.autoComplete()
          console.log(`autoComplete ${autoComplete}`)
          autoComplete.search(value, function (status: any, result: any) {
            console.log(`status = ${status}, result = ${result}`)
            if (status === 'complete') {
              // 搜索成功时，result 即是对应的匹配数据
              result.tips.forEach((e: any, i: any) => {
                e.label = e.district + e.name
                e.value = e.label
              })
              console.log('result = ', result);
              // return result.tips
              setAddressList(result.tips)
            }
          });
        }, 500)

      }}
    />
  </ProForm.Item>
}

export default MapAutoComplete
